using Avalonia;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using OpenCvSharp;
using System;
using System.Globalization;
using System.IO;
using Avalonia.Data.Converters;

namespace CameraManager.Converters;

public class MatToImageConverter : IValueConverter
{
    public static MatToImageConverter Instance { get; } = new();

    public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is not Mat mat || mat.Empty())
            return null;

        try
        {
            using var memory = new MemoryStream();
            mat.WriteToStream(memory, ".png");
            memory.Position = 0;
            
            return new Bitmap(memory);
        }
        catch
        {
            return null;
        }
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

public class BoolToStringConverter : IValueConverter
{
    public static BoolToStringConverter Instance { get; } = new();

    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is not bool boolValue) return "未知";
        
        var options = parameter?.ToString()?.Split('|') ?? new[] { "是", "否" };
        return boolValue ? options[0] : options[1];
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is not string strValue)
            return false;
        var options = parameter?.ToString()?.Split('|') ?? new[] { "是", "否" };
        if (strValue == options[0])
            return true;
        return false;
    }
}
